﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PatternRegistUC
{
    /// <summary>
    /// Register pattern user control
    /// </summary>
    public partial class PatternRegist : DevComponents.DotNetBar.Office2007Form
    {
        #region Attributs and Getter/Setter
        private FVIL.Forms.CFviImageView m_imageView;
        public EventHandler eventCloseForm;
        public EventHandler eventSaveForm;
        private string m_patternName;
        private string m_patternFolder;
        private FVIL.Data.CFviImage m_patternImage;
        private FVIL.Data.CFviImage m_originalImage;
        private bool m_isEmptyText; // To Re-enter pattern name if empty

        public string PatternFolder
        {
            get { return m_patternFolder; }
            set { m_patternFolder = value; }
        }

        public string PatternName
        {
            get { return m_patternName; }
            set { m_patternName = value; }
        }

        public FVIL.Forms.CFviImageView ImageView
        {
            get { return m_imageView; }
            set { m_imageView = value; }
        }
        #endregion

        public PatternRegist()
        {
            InitializeComponent();
        }

        #region Logic functions
        /// <summary>
        /// Initialize parameters
        /// </summary>
        /// <param name="imageView"></param>
        public void setImageView(FVIL.Forms.CFviImageView imageView)
        {
            m_imageView = imageView;
            m_imageView.Display.OverlayPatternRegist.Active = true;
            m_imageView.Refresh();
        }

        /// <summary>
        /// Algorithm implementation to detect pattern
        /// </summary>
        /// <returns>true if pattern is detected</returns>
        private bool detectPattern()
        {
            m_imageView.Image = m_originalImage; // Reset output image
            // Cut pattern image from original image and register rectangle
            m_patternImage = new FVIL.Data.CFviPattern(m_originalImage,
                m_imageView.Display.OverlayPatternRegist.RegistRect.ToCFviRectangle(),
                m_imageView.Display.OverlayPatternRegist.CenterMark.ToCFviPoint());
            // Draw pattern bouding rectangle
            m_imageView.Image = drawPattern(m_originalImage,
                m_imageView.Display.OverlayPatternRegist.RegistRect.ToCFviRectangle());
            m_imageView.Refresh();
            return true;
        }

        /// <summary>
        /// Draw pattern bouding rectangle
        /// </summary>
        /// <param name="src"></param>
        /// <param name="rectangle"></param>
        /// <returns></returns>
        public static FVIL.Data.CFviImage drawPattern(FVIL.Data.CFviImage src, 
            FVIL.Data.CFviRectangle rectangle)
        {
            FVIL.Data.CFviImage dst = new FVIL.Data.CFviImage();
            FVIL.GDI.CFviDisplay display = new FVIL.GDI.CFviDisplay();
            display.Image = src;
            display.DisplayRect = src.Window;
            FVIL.GDI.CFviOverlay pOverlay0 = new FVIL.GDI.CFviOverlay();
            pOverlay0.Scaling = true;
            display.Overlays.Add(pOverlay0);

            FVIL.GDI.CFviGdiRectangle gRectangle = new FVIL.GDI.CFviGdiRectangle(rectangle);
            gRectangle.Pen.Color = System.Drawing.Color.Red;
            gRectangle.Pen.Width = 2;
            pOverlay0.Figures.Add(gRectangle);
            display.SaveImage(dst, display.DisplayRect, 1.0);
            return dst;
        }

        /// <summary>
        /// Save pattern image with name in text box
        /// </summary>
        private void savePattern()
        {
            if (!System.String.IsNullOrEmpty(tbPatternName.Text))
            {
                m_patternName = tbPatternName.Text;
                m_patternName = checkExistance();
            }
            else
            {
                MessageBox.Show("が空白です。再度ご確認してから入力してください。", "警報", 
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                m_isEmptyText = true;
                return;
            }
            string fileName = m_patternFolder + m_patternName + ".bmp";
            m_patternImage.Save(fileName); // save pattern
            this.Close();
        }

        /// <summary>
        /// Rename pattern if exist
        /// </summary>
        /// <returns></returns>
        public string checkExistance()
        {
            string fullFilePath = m_patternFolder + m_patternName + ".bmp";
            string fileNameExtend = m_patternName;
            if (System.IO.File.Exists(fullFilePath))
            {
                int index = 1;
                fileNameExtend = m_patternName + "(" + index + ")";
                while (System.IO.File.Exists(m_patternFolder + fileNameExtend + ".bmp"))
                    fileNameExtend = m_patternName + "(" + ++index + ")";
            }
            return fileNameExtend;
        }
        #endregion

        #region Events on form
        private void PatternRegist_Load(object sender, EventArgs e)
        {
            m_originalImage = m_imageView.Image;
            tbPatternName.Select();
            m_patternImage = new FVIL.Data.CFviImage();
            m_patternFolder = "";
            timerUpdateCenter.Start();
        }

        private void PatternRegist_FormClosed(object sender, FormClosedEventArgs e)
        {
            OnCloseForm();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            OnCloseForm();
            this.Close();
        }

        private void btnSavePattern_Click(object sender, EventArgs e)
        {
            m_isEmptyText = false;
            savePattern();
            if (!m_isEmptyText)
                OnSaveForm();
        }

        public virtual void OnCloseForm()
        {
            EventHandler handler = eventCloseForm;
            if (handler != null)
            {
                handler(null, EventArgs.Empty);
            }
            hideRegistRegion();
        }

        public virtual void OnSaveForm()
        {
            EventHandler handler = eventSaveForm;
            if (handler != null)
            {
                handler(null, EventArgs.Empty);
            }
            hideRegistRegion();
        }

        /// <summary>
        /// Inactive pattern register region
        /// </summary>
        private void hideRegistRegion()
        {
            m_imageView.Display.OverlayPatternRegist.Active = false;
            m_imageView.Image = m_originalImage;
            m_imageView.Refresh();
        }

        private void btnDetect_Click(object sender, EventArgs e)
        {
            detectPattern();
            if (detectPattern()) btnSavePattern.Enabled = true;
            tbPatternName.Select();
        }

        private void timerUpdateCenter_Tick(object sender, EventArgs e)
        {
            // Update center mark
            m_imageView.Display.OverlayPatternRegist.CenterMark.X =
                m_imageView.Display.OverlayPatternRegist.RegistRect.Left;
            m_imageView.Display.OverlayPatternRegist.CenterMark.Y =
                m_imageView.Display.OverlayPatternRegist.RegistRect.Top;
            m_imageView.Refresh();
        }
        #endregion
    }
}
